import { useState, useEffect } from 'react';
import { Card, Text, Group, Stack, TextInput, Button, Pagination, Alert } from '@mantine/core';
import { IconPlant2, IconFileDescription, IconBulb, IconSearch, IconAlertCircle } from '@tabler/icons-react';
import { plantDiseaseApi } from '../../services/api';

interface DiseaseInfo {
    id: number;
    en_name: string;
    cn_name: string;
    description: string;
    suggestion: string;
    img_url: string;
}

interface PaginationInfo {
    page: number;
    per_page: number;
    total: number;
    pages: number;
    has_next: boolean;
    has_prev: boolean;
}

const PlanDiseaseSearch = () => {
    const [keyword, setKeyword] = useState('');
    const [loading, setLoading] = useState(false);
    const [results, setResults] = useState<DiseaseInfo[]>([]);
    const [pagination, setPagination] = useState<PaginationInfo>({
        page: 1,
        per_page: 10,
        total: 0,
        pages: 0,
        has_next: false,
        has_prev: false
    });
    const [error, setError] = useState<string | null>(null);
    const [hasSearched, setHasSearched] = useState(false);

    const fetchDiseases = async (page = 1) => {
        setLoading(true);
        setError(null);

        try {
            const response = await plantDiseaseApi.getPlantDiseases({
                page,
                per_page: 10,
                cn_name: keyword.trim() || undefined,
                en_name: keyword.trim() || undefined
            });

            setResults(response.diseases || []);
            setPagination(response.pagination || {
                page: 1,
                per_page: 10,
                total: 0,
                pages: 0,
                has_next: false,
                has_prev: false
            });
        } catch (error) {
            console.error('Search failed:', error);
            setError(error instanceof Error ? error.message : '搜索失败，请稍后重试');
            setResults([]);
        } finally {
            setLoading(false);
            setHasSearched(true);
        }
    };

    const handleSearch = () => {
        fetchDiseases(1);
    };

    const handlePageChange = (page: number) => {
        fetchDiseases(page);
    };

    return (
        <Stack gap="lg" p="md">
            <Group gap="sm">
                <TextInput
                    placeholder="输入关键字搜索病虫害信息"
                    value={keyword}
                    onChange={(event) => setKeyword(event.currentTarget.value)}
                    style={{ flex: 1 }}
                />
                <Button
                    onClick={handleSearch}
                    loading={loading}
                    leftSection={<IconSearch size={20} />}
                >
                    搜索
                </Button>
            </Group>

            {results.length > 0 && (
                <Stack gap="md">
                    {results.map((result, index) => (
                        <Card key={index} withBorder shadow="sm" padding="md">
                            <Group align="flex-start" gap="lg">
                                {/* <Card.Section style={{ width: '300px', minWidth: '300px' }}>
                                    <img
                                        src={result.img_url || '/demo1.JPG'}
                                        alt={result.cn_name}
                                        style={{
                                            padding: '10px',
                                            width: '100%',
                                            height: '300px',
                                            objectFit: 'cover',
                                            borderRadius: '15px'
                                        }}
                                    />
                                </Card.Section> */}
                                <Stack gap="md" style={{ flex: 1 }}>
                                    <Card withBorder shadow="xs" padding="md">
                                        <Group gap="xs">
                                            <IconPlant2 size={20} style={{ color: 'var(--mantine-color-green-6)' }} />
                                            <Text fw={500} c="gray.7">病虫害名称</Text>
                                        </Group>
                                        <Text size="lg" mt="xs">{result.cn_name} ({result.en_name})</Text>
                                    </Card>

                                    <Card withBorder shadow="xs" padding="md">
                                        <Group gap="xs">
                                            <IconFileDescription size={20} style={{ color: 'var(--mantine-color-blue-6)' }} />
                                            <Text fw={500} c="gray.7">详细描述</Text>
                                        </Group>
                                        <Text size="lg" mt="xs" style={{ whiteSpace: 'pre-wrap' }}>{result.description}</Text>
                                    </Card>

                                    <Card withBorder shadow="xs" padding="md">
                                        <Group gap="xs">
                                            <IconBulb size={20} style={{ color: 'var(--mantine-color-yellow-6)' }} />
                                            <Text fw={500} c="gray.7">防治建议</Text>
                                        </Group>
                                        <Text size="lg" mt="xs" style={{ whiteSpace: 'pre-wrap' }} dangerouslySetInnerHTML={{ __html: result.suggestion }} />
                                    </Card>
                                </Stack>
                            </Group>
                        </Card>
                    ))}
                </Stack>
            )}

            {!loading && hasSearched && results.length === 0 && !error && (
                <Alert icon={<IconAlertCircle size={16} />} color="gray" title="提示">
                    未找到相关病虫害信息
                </Alert>
            )}

            {error && (
                <Alert icon={<IconAlertCircle size={16} />} title="错误" color="red" withCloseButton onClose={() => setError(null)}>
                    {error}
                </Alert>
            )}

            {results.length > 0 && pagination.pages > 1 && (
                <Group mt="xl">
                    <Pagination
                        total={pagination.pages}
                        value={pagination.page}
                        onChange={handlePageChange}
                    />
                </Group>
            )}
        </Stack>
    );
};

export default PlanDiseaseSearch;